package swissmap.RMAP.utils;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;

import swissmap.Constants;


public class Utilities {

	public static BufferedImage createEmptyTileImage(){//MapSource mapSource) {
		int tileSize = 256;//mapSource.getMapSpace().getTileSize();
		Color color = Color.WHITE; //mapSource.getBackgroundColor();
		BufferedImage emptyImage = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = emptyImage.createGraphics();
		try {
			g.setColor(color);
			g.fillRect(0, 0, tileSize, tileSize);
		} finally {
			g.dispose();
		}
		return emptyImage;
	}

	public static byte[] createEmptyTileData(){//MapSource mapSource) {
		BufferedImage emptyImage = createEmptyTileImage();//mapSource);
		ByteArrayOutputStream buf = new ByteArrayOutputStream(4096);
		try {
			ImageIO.write(emptyImage, "jpg"/*mapSource.getTileImageType().getFileExt()*/, buf);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		byte[] emptyTileData = buf.toByteArray();
		return emptyTileData;
	}
	
	
	/**
	 * 
	 * @param x
	 * @param y
	 * @param zoomlevel of current layer
	 * @param maxzoom highest resolution map zoomlevel
	 * @return
	 */
	public static byte[] tileProvider(int x, int y, int zoomlevel, int maxzoom){
		//String[] res={"10k","20k","25k","50k"}; //,"100k","200k"};
		
		File f;
		f=new File(Constants.basePath+"raw"+File.separator+(Constants.map?"map":"ortho")+File.separator+Constants.res_arr[zoomlevel]+"\\"+Constants.intoToString(x)+"\\"+Constants.intoToString(y)+".jpeg");//Input
		
		FileInputStream fileInputStream;
		byte[] data=null;
		if(!f.exists()){
			data=createEmptyTileData();
		}
		else{
			try {
				fileInputStream = new FileInputStream(f);
				data = new byte[(int) f.length()];
				fileInputStream.read(data);
				fileInputStream.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
       
		return data;
	}
	
}
